/**
 * Created by 小敏哥on 2017/3/8.
 */
import React, {Component} from 'react';
import {Toast} from 'antd-mobile';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import {connect} from 'react-redux';
import {currentCarIndex} from '../../actions/homeAction';
import {getCheckDate, updateCar, deleteCar, getCarInfo} from '../../actions/updateCarInfoAction';
import {getCalculation} from '../../actions/calculatorAction';
import DropDownBox from '../../components/updateCarInfo/dropDownBox';
import PageBar from '../../components/common/pageBar';
import style from './index.scss';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import ReModal from '../../components/common/reModal';
import DatePicker from 'react-mobile-datepicker';
import '../../../styles/datePickerAdapt.scss';
import ItemList from '../../components/common/itemList';
import ItemWithRightArrow from '../../components/common/itemWithRightArrow';
import UserGuide from '../../components/updateCarInfo/userGuide'

class UpdateCarInfo extends Component {
    constructor(props) {
        super(props);
        this.saveChange = this.saveChange.bind(this);
        this.changeCheckDate = this.changeCheckDate.bind(this);
        this.getCurrentValidityDate = this.getCurrentValidityDate.bind(this);
        this.deleteCar = this.deleteCar.bind(this);
        this.state = {
            registerDate: '请选择',//注册时间
            validityDate: '请选择',//有效时间
            dateList: [],//有效期时间列表
            dialogExist: false,//当前是否有弹框出现
            selectedIndex: 0, //默认选中项
            carId: props.params.carId ? props.params.carId : props.carList.cars[props.currentCarIndex].carId,//车辆id
            carNumber: decodeURIComponent(props.params.carNumber ? props.params.carNumber : props.carList.cars[props.currentCarIndex].carNumber),//车牌
            carCode: '',//车辆code
            engineNumber: '',//引擎号码
            isOpenDatePicker: false,//是否显示日期选择器
        };
        //此处定义app返回键的回调函数
        /*window.cxyClickBack = () => {
            history.back();
        };*/
     //   this.backMeanSureInstance = new BackMeanSure(this.goHome.bind(this), 'updateCarInfo');
    }


    //返回首页
    goHome(back, stay, toUrl) {
        /*if (typeOfBrowser.getChannelOfBrowser() == 'app') {
            //app直接关闭当前webview回到年检提醒
            common.closeAppView();
        }
        else {*/
         /*   history.pushState({}, '', '');
            let backNumber = -1 * history.length + 1;
            history.go(backNumber);*/
      //  }
        history.back();
    }


    /*    //清除ant弹框
     closeAliModal() {
     let div = document.querySelector(".am-modal-wrap");
     if (div) {
     div = div.parentNode;
     if (div) {
     div.parentNode.removeChild(div);
     }
     }
     }*/


    formatDate(date) {
        if (date.getMonth) {
            let monthString = date.getMonth() + 1 < 10 ? ('0' + (date.getMonth() + 1).toString()) : (date.getMonth() + 1).toString();
            let dateString = date.getDate() < 10 ? ('0' + date.getDate().toString()) : date.getDate().toString();
            return date.getFullYear() + '-' + monthString + '-' + dateString;
        }
        return date;
    }


    getCarInfo() {
        this.props.dispatch(getCarInfo({
            carNumber: this.state.carNumber,
            carId: this.state.carId
        }, (result) => {
            this.setState({
                registerDate: result.registerDate ? new Date(result.registerDate) : this.state.registerDate,
                validityDate: result.checkDate ? result.checkDate : this.state.validityDate,
                carCode: result.carCode ? result.carCode : '',
                engineNumber: result.engineNumber ? result.engineNumber : '',
            });

            setTimeout(() => {
                this.state.registerDate && this.changeCheckDate(this.formatDate(this.state.registerDate), false);
            }, 0)
        }));
    }

    componentWillMount() {
    }

    componentWillUnmount() {
        /*  this.closeAliModal();*/
        AlipayJSOperation.removeLeftButtonEvent();
    }

    componentDidMount() {
        /* if (this.props.carList == undefined) {
         window.history.go(-1)
         }
         else {*/
        this.getCarInfo();
      /*  var pattern = /(\S+)index.html/g;
        var path = pattern.exec(window.location.href)[1];*/
        AlipayJSOperation.setRightButtonStatus(false);
        /* AlipayJSOperation.setMenuAsIconButton(path+'images/icon_del.png');

         AlipayJSOperation.setMenuButtonEvent(this.deleteCar);*/
        //设置标题
        AlipayJSOperation.setTitle('编辑车辆信息');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');

        document.querySelector("title").innerHTML = "编辑车辆信息";
       // this.backMeanSureInstance.bindBackMeansure();
        // }
        SendCxytjMessage.sendMessage({eventId: 'H5_E_Interspection_EnterEditCarDatapage'});
    }

    //删除车辆信息
    deleteCar() {
        //防止弹框多次出现
        if (!this.state.dialogExist) {
            ReModal.confirm('确定要删除此车辆吗?', () => {
                this.setState({
                    dialogExist: false
                });
                this.props.dispatch(deleteCar({
                    carId: this.state.carId,
                    carNumber: this.state.carNumber
                }, () => {
                    this.props.dispatch(currentCarIndex(0));
                    //this.context.router.push('/');
                    this.goHome();
                }));
                SendCxytjMessage.sendMessage({eventId: 'Insepection_DeleteCar'});
            });
        }
    }

    //获取计算结果后跳转到首页
    saveChange() {
        if (this.state.validityDate == '请选择') {
            Toast.info('请选择注册日期！', 2);
            return;
        }
        // let current = this.props.carList.cars[this.props.currentCarIndex];
        this.props.dispatch(getCalculation({
            carId: this.state.carId,
            carNumber: this.state.carNumber,
            registerDate: this.formatDate(this.state.registerDate),
            checkDate: this.state.validityDate,
            carCode: this.state.carCode,
            engineNumber: this.state.engineNumber,
        }, () => {
            this.context.router.replace(`/yearlyCheckDetail/${encodeURIComponent(this.state.carNumber)}/${ this.state.carId}/update`);
        }));
        SendCxytjMessage.sendMessage({eventId: 'Insepection_SaveCarData'});
    }

    //获取最终的有效时间
    getCurrentValidityDate(index) {
        this.setState({
            validityDate: this.state.dateList[index].label,
            selectedIndex: index,
        });
    }

    //获取数据后更新有效时间列表
    changeCheckDate(registerDate, init = true) {
        if (registerDate != '请选择') {
            this.props.dispatch(getCheckDate({registerDate: registerDate}, (result) => {
                var dateList = [];
                for (var i = 0; i < result.length; i++) {
                    dateList.push({
                        value: i,
                        label: result[i].checkDate
                    });
                }
                this.setState({
                    dateList: dateList
                });
                //默认选中项，传入FALSE时不做操作
                init && this.getCurrentValidityDate(this.getDropDownIndex(dateList));
            }));
        }
    }

    showDropDrown() {
        if (this.state.registerDate == '请选择') {
            Toast.info("请选择注册日期！", 1);
        }
        else {
            DropDownBox.showComponent(true)
        }
    }


    getDropDownIndex(data) {
        var now = new Date();
        var dateCache;
        for (var i = data.length - 1; i >= 0; i--) {
            dateCache = new Date(data[i].label);
            if (now - dateCache < 30 * 24 * 60 * 60 * 1000) {
                return i;
            }
        }
        return 0;

    }

    render() {
        return <div className={style.calculatorContainer}>
            <PageBar title="编辑车辆信息"/>
            <UserGuide img1="./images/registerDateGuide.png" img2="./images/validityDateGuide.png"/>
            <div className={style.tips}>
                <div
                    className={style.tipsMessage}>{'请输入' + this.state.carNumber + '车辆的注册信息'}</div>
                <div onClick={this.deleteCar}><img src="./images/update_del.png"/>
                    <div>删除</div>
                </div>
            </div>
            <div className={style.calculatorMessage}>
                {
                    <ItemList borderPaddingLeft="16px" borderPaddingRight="16px">
                        <ItemWithRightArrow>
                            <div className={style.registerDateItem}>
                                <span>车辆注册日期</span>
                                <img src="./images/icon_warn_darkblue.png" onClick={()=>{ReModal.showOnlyComponent(<img className={style.tipsImage} src="./images/registerDate.jpg"/>)}}/>
                                <span onClick={() => {
                                    this.setState({
                                        isOpenDatePicker: true
                                    });
                                }}>{this.state.registerDate == '请选择' ? this.state.registerDate : this.formatDate(this.state.registerDate)}</span>
                            </div>
                        </ItemWithRightArrow>
                        <ItemWithRightArrow>
                            <div className={style.validityDateItem}>
                                <span>检验有效期至</span>
                                <img src="./images/icon_warn_darkblue.png"  onClick={()=>{ReModal.showOnlyComponent(<img className={style.tipsImage} src="./images/validityDate.jpg"/>)}}/>
                                <span  onClick={() => {
                                    this.showDropDrown();
                                }}>{this.state.validityDate}</span>
                            </div>
                        </ItemWithRightArrow>
                    </ItemList>
                }
            </div>
            <div className={style.buttonContainer}>
                <button onClick={this.saveChange}>保存</button>
            </div>
            <article className={style.calculatorWarnning}>
                <div className={style.warningTitle}>
                    <div className={style.titleLine}></div>
                    <h1>年检条件计算说明</h1>
                    <div className={style.titleLine}></div>
                </div>
                <p>
                    1、输入准确的车辆信息，系统会智能计算出车辆的年检状态，以及下一次年检的类型。如果进入预约周期，系统还能自动提醒您需要准备哪些资料，该如何办理。如果一不小心逾期，系统还能协助您如何尽量避免损失。
                </p>
                <p>
                    2、本计算方式只适用于7座以下的蓝牌小轿车。
                </p>
            </article>
            <DropDownBox data={this.state.dateList} selectedIndex={this.state.selectedIndex}
                         onChange={(index) => {
                             this.getCurrentValidityDate(index)
                         }}></DropDownBox>
            <div>
                <DatePicker
                    value={this.state.registerDate != '请选择' ? this.state.registerDate : new Date()}
                    isOpen={this.state.isOpenDatePicker}
                    theme="ios"
                    dateFormat={['YYYY年', 'MM月', 'DD日']}
                    max={new Date()}
                    onSelect={(date) => {
                        this.changeCheckDate(this.formatDate(date));
                        this.setState({
                            registerDate: date,
                            isOpenDatePicker: false
                        });
                    }}
                    onCancel={() => {
                        this.setState({
                            isOpenDatePicker: false
                        });
                    }}/>
            </div>
        </div>
    }
}

//react router跳转时使用了context，此处需要显式声明
UpdateCarInfo.contextTypes = {
    router: React.PropTypes.object.isRequired
};

function mapStateToProps(state) {
    return Object.assign({}, state.homeInfo);
}

export default connect(mapStateToProps)(UpdateCarInfo)
